package com.example.websession;

import java.util.Arrays;
import java.util.Date;
import java.util.function.Consumer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value="/home")
@SpringBootApplication
public class Web0920Application {

	private static Consumer<Object> cs = System.out::println;

	public static void main(String[] args) {
		ConfigurableApplicationContext ctx = SpringApplication.run(Web0920Application.class, args);
		cs.accept("程序已启动");
		
//		studyContext(ctx);
	}
	
	@Autowired
	private HttpServletRequest req;
	
	@Autowired
	private HttpServletResponse resp;
	
	public static void studyContext(ConfigurableApplicationContext ctx) {
		cs.accept("++++++studyContext++++++\nBeanDefinitionCount=" + ctx.getBeanDefinitionCount());
		String[] beanNames = ctx.getBeanDefinitionNames();
		cs.accept("beanNames.length=" + beanNames.length);
		cs.accept("输出Bean的名称：");
		Arrays.stream(beanNames).forEach((name)->{
			cs.accept("session name=" + name);
			
//			Object bean = ctx.getBean(name);
//			if(bean != null) {
//				String beanStr = bean.toString();
//				if (beanStr.toLowerCase().contains("session")) {
//					cs.accept("session name=" + name + ", beanStr=" + beanStr);
//				}
//			}
		});

		cs.accept("++++++studyContext 结束++++++");
	}
	
	@GetMapping(value="/get")
	public String get() {
		cs.accept("\nreq=" + req);
		cs.accept("req=" + req.getClass());

		// 请求中的session id：旧值
		String sid = req.getRequestedSessionId();
		cs.accept("req sid 1=" + sid);
		
		// 请求处理后的，新值
		HttpSession hsess = req.getSession();
		cs.accept("req sess=" + hsess);
		cs.accept("createTime=" + new Date(hsess.getCreationTime()));
		cs.accept("LastAccessedTime=" + new Date(hsess.getLastAccessedTime()));
		cs.accept("MaxInactiveInterval=" + hsess.getMaxInactiveInterval() + "秒");
		
		cs.accept("hsess.getId()=" + hsess.getId());
		cs.accept("hsess.isNew()=" + hsess.isNew());
		
		// session的属性
		hsess.setAttribute("name", "lib210924");
		hsess.setAttribute("age", 3);
		
		cs.accept("session.name=" + hsess.getAttribute("name"));
		cs.accept("session.age=" + hsess.getAttribute("age"));
		cs.accept("session.notexists=" + hsess.getAttribute("notexists"));
		
		return new Date().toString();
	}

}
